import { getHost } from '@/store/system/utils';
import useUserStore from '@/store/user';
import { getToken } from '@/store/user/utils';
import { joinUrl } from '@/utils/file/format';
import type { UploadFile } from '@/views/modules/system/folder/data/types';
import { message } from 'ant-design-vue';
import axios from 'axios';

interface ExportData {
  url: string;
  data?: any;
  fileName: string;
  method: 'POST' | 'GET';
  params?: any;
}
// 导出文件接口
// 已使用:代码下载
export const exportFile = async (config: ExportData) => {
  const userStore = useUserStore();
  const host = getHost(config.url);
  try {
    const response = await axios({
      url: host,
      method: config.method,
      headers: {
        Authorization: `Bearer ${userStore.$state.token}`,
      },
      responseType: 'blob',
      params: config.params,
      data: config.data,
      timeout: 0,
    });

    const blob = await response.data;
    const href = window.URL.createObjectURL(blob);

    const link = document.createElement('a');
    link.href = href;
    link.download = config.fileName || '自定义文件';
    link.click();

    window.URL.revokeObjectURL(href);
  } catch (error: any) {
    message.warning('Error exporting file!');
  }
};

interface UploadData {
  url: string;
  formData: FormData;
}

/* 上传文件 */
export const uploadFile = async (data: UploadData) => {
  const userStore = useUserStore();
  await fetch(data.url, {
    body: data.formData,
    method: 'POST',
    headers: {
      Authorization: `Bearer ${userStore.$state.token}`,
    },
  });
};

/**
 * @description: 通用上传接口
 * @param {url} 后端接受文件的路径
 * @return {*}
 */
type FileUploader = {
  params?: object;
  files: UploadFile[];
  url: string;
  method?: string;
};
export const fileUploader = async (config: FileUploader) => {
  const http = axios.create();
  const host = getHost();
  const token = getToken();
  const formData = new FormData();
  const cancelToken = ref(axios.CancelToken.source());
  Array.from(config.files).forEach(file => {
    formData.append('files', file.file, file.path || file.file.name);
  });
  const response = await http({
    method: config.method || 'post',
    url: joinUrl(host, config.url),
    data: formData,
    params: config.params,
    headers: {
      'Content-Type': 'multipart/form-data',
      Authorization: `Bearer ${token}`,
    },
    cancelToken: cancelToken.value.token,
    timeout: 0,
  });
  return {
    cancelToken: cancelToken.value,
    response: response.data,
  };
};
